#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称: notification_management_api.py
完整存储路径: backend/api/admin/notification_management_api.py
功能说明:
    通知公告管理API接口，用于管理员发布和管理系统通知、公告信息
    
路由说明:
    - GET /api/admin/notifications - 获取通知列表
    - POST /api/admin/notifications - 创建新通知
    - PUT /api/admin/notifications/<id> - 更新通知
    - DELETE /api/admin/notifications/<id> - 删除通知
    - POST /api/admin/notifications/<id>/publish - 发布通知
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from functools import wraps
from datetime import datetime
from backend.models.notification import Notification
from backend.models.user import User
from backend.infrastructure.database import db
from backend.services.unified_log_service import log_service
from sqlalchemy import and_, or_

notification_management_api = Blueprint('notification_management_api', __name__)

# 管理员权限装饰器
def admin_required(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        from flask_jwt_extended import get_jwt
        claims = get_jwt()
        roles = claims.get('roles', [])
        if 'admin' not in roles:
            return jsonify({'success': False, 'message': '仅管理员可操作'}), 403
        return fn(*args, **kwargs)
    return wrapper

@notification_management_api.route('/api/admin/notifications', methods=['GET'])
@jwt_required()
@admin_required
def list_notifications():
    """获取通知列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        notification_type = request.args.get('type')
        status = request.args.get('status')
        search_term = request.args.get('search', '').strip()
        
        # 构建查询 - 只显示管理员创建的主通知记录（草稿或已发布状态）
        # 不显示分发给具体用户的个人通知
        current_user_id = get_jwt_identity()
        query = Notification.query.filter(
            and_(
                Notification.created_by.isnot(None),  # 有创建者的通知（管理员创建的）
                or_(
                    Notification.status == 'draft',      # 草稿状态
                    Notification.status == 'published'   # 已发布状态
                )
            )
        )
        
        # 类型筛选
        if notification_type:
            query = query.filter(Notification.notification_type == notification_type)
        
        # 状态筛选
        if status:
            query = query.filter(Notification.status == status)
        
        # 搜索功能
        if search_term:
            query = query.filter(
                or_(
                    Notification.title.like(f'%{search_term}%'),
                    Notification.content.like(f'%{search_term}%')
                )
            )
        
        # 分页查询
        pagination = query.order_by(Notification.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        notifications = [notification.to_dict() for notification in pagination.items]
        
        return jsonify({
            'success': True,
            'data': {
                'notifications': notifications,
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                    'total': pagination.total,
                    'pages': pagination.pages,
                    'has_next': pagination.has_next,
                    'has_prev': pagination.has_prev
                }
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取通知列表失败: {str(e)}'
        }), 500

@notification_management_api.route('/api/admin/notifications', methods=['POST'])
@jwt_required()
@admin_required
def create_notification():
    """创建新通知"""
    try:
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        # 验证必填字段
        required_fields = ['title', 'content', 'notification_type']
        for field in required_fields:
            if not data.get(field):
                return jsonify({
                    'success': False,
                    'message': f'缺少必填字段: {field}'
                }), 400
        
        # 验证通知类型
        notification_type = data['notification_type']
        
        # 获取目标用户列表
        target_user_type = data.get('target_user_type', 'all')
        target_users = []
        
        if target_user_type == 'all':
            # 获取所有用户
            target_users = User.query.all()
        elif target_user_type == 'admin':
            # 获取管理员用户
            target_users = User.query.filter(User.roles.any(name='admin')).all()
        elif target_user_type == 'doctor':
            # 获取医生用户
            target_users = User.query.filter(User.roles.any(name='doctor')).all()
        elif target_user_type == 'parent':
            # 获取家长用户
            target_users = User.query.filter(User.roles.any(name='parent')).all()
        else:
            target_users = User.query.all()  # 默认所有用户
        
        # 根据status参数决定是保存草稿还是立即发送
        status = data.get('status', 'draft')  # 默认保存为草稿
        
        if status == 'draft':
            # 草稿模式：只创建一条主通知记录，不验证目标用户是否存在
            notification = Notification(
                title=data['title'],
                content=data['content'],
                notification_type=notification_type,
                priority=data.get('priority', 'normal'),
                status='draft',
                target_users=target_user_type,
                created_by=current_user_id,
                scheduled_at=None,  # 暂时简化处理
                expire_at=None      # 暂时简化处理
            )
            db.session.add(notification)
            db.session.commit()
            
            return jsonify({
                'success': True,
                'data': notification.to_dict(),
                'message': '通知草稿保存成功'
            })
        else:
            # 发送模式：检查目标用户并为每个用户创建通知记录
            if not target_users:
                return jsonify({
                    'success': False,
                    'message': f'目标用户类型"{target_user_type}"下没有找到用户'
                }), 400
            
            # 发送模式：为每个目标用户创建通知记录
            notifications_created = []
            for user in target_users:
                notification = Notification(
                    user_id=user.id,
                    title=data['title'],
                    content=data['content'],
                    notification_type=notification_type,
                    priority=data.get('priority', 'normal'),
                    status='unread',  # 用户个人通知状态
                    target_users=target_user_type,
                    # 不设置created_by，个人通知不在管理列表显示
                    sent_at=datetime.now(),
                    published_at=datetime.now()
                )
                db.session.add(notification)
                notifications_created.append(notification)
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='CREATE',
            table_name='notifications',
            record_id=len(notifications_created),
            details=f'发送通知: {data["title"]}, 发送给 {len(notifications_created)} 个用户'
        )
        
        return jsonify({
            'success': True,
            'data': {
                'total_sent': len(notifications_created),
                'notifications': [n.to_dict() for n in notifications_created[:5]]  # 返回前5个作为样例
            },
            'message': f'通知发送成功，共发送给 {len(notifications_created)} 个用户'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'创建通知失败: {str(e)}'
        }), 500

@notification_management_api.route('/api/admin/notifications/<int:notification_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_notification(notification_id):
    """更新通知"""
    try:
        notification = Notification.query.get_or_404(notification_id)
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        # 检查通知状态，已发布的通知不能修改内容
        if notification.status == 'sent':
            return jsonify({
                'success': False,
                'message': '已发送的通知不能修改'
            }), 400
        
        # 更新字段
        if 'title' in data:
            notification.title = data['title']
        if 'content' in data:
            notification.content = data['content']
        if 'target_user_type' in data:
            notification.target_user_type = data['target_user_type']
        if 'priority' in data:
            notification.priority = data['priority']
        if 'scheduled_at' in data:
            notification.scheduled_at = datetime.fromisoformat(data['scheduled_at']) if data['scheduled_at'] else None
        if 'expire_at' in data:
            notification.expire_at = datetime.fromisoformat(data['expire_at']) if data['expire_at'] else None
        
        notification.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='UPDATE',
            table_name='notifications',
            record_id=notification.id,
            details=f'更新通知: {notification.title}'
        )
        
        return jsonify({
            'success': True,
            'data': notification.to_dict(),
            'message': '通知更新成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'更新通知失败: {str(e)}'
        }), 500

@notification_management_api.route('/api/admin/notifications/<int:notification_id>/publish', methods=['POST'])
@jwt_required()
@admin_required
def publish_notification(notification_id):
    """发布通知"""
    try:
        notification = Notification.query.get_or_404(notification_id)
        current_user_id = get_jwt_identity()
        
        # 检查通知状态
        if notification.status == 'published':
            return jsonify({
                'success': False,
                'message': '通知已经发布'
            }), 400
        
        # 获取目标用户列表
        target_user_type = notification.target_users or 'all'
        target_users = []
        
        if target_user_type == 'all':
            target_users = User.query.all()
        elif target_user_type == 'admin':
            target_users = User.query.filter(User.roles.any(name='admin')).all()
        elif target_user_type == 'doctor':
            target_users = User.query.filter(User.roles.any(name='doctor')).all()
        elif target_user_type == 'parent':
            target_users = User.query.filter(User.roles.any(name='parent')).all()
        else:
            target_users = User.query.all()
        
        # 检查是否有目标用户
        if not target_users:
            return jsonify({
                'success': False,
                'message': f'目标用户类型"{target_user_type}"下没有找到用户，无法发布'
            }), 400
        
        # 为每个目标用户创建个人通知记录
        notifications_created = 0
        for user in target_users:
            user_notification = Notification(
                user_id=user.id,
                title=notification.title,
                content=notification.content,
                notification_type=notification.notification_type,
                priority=notification.priority,
                status='unread',  # 用户的个人通知状态为未读
                related_type=notification.related_type,
                related_id=notification.related_id,
                template_id=notification.template_id,
                target_users=notification.target_users,
                # 不设置created_by，这样个人通知就不会在管理列表中显示
                sent_at=datetime.now()
            )
            db.session.add(user_notification)
            notifications_created += 1
        
        # 更新原通知状态和发送数量
        notification.status = 'published'
        notification.published_at = datetime.now()
        notification.sent_at = datetime.now()
        notification.sent_count = notifications_created  # 记录实际发送数量
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='PUBLISH',
            table_name='notifications',
            record_id=notification.id,
            details=f'发布通知: {notification.title}, 发送给 {notifications_created} 个用户'
        )
        
        return jsonify({
            'success': True,
            'data': {
                'notification': notification.to_dict(),
                'sent_count': notifications_created
            },
            'message': f'通知发布成功，已发送给 {notifications_created} 个用户'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'发布通知失败: {str(e)}'
        }), 500

@notification_management_api.route('/api/admin/notifications/<int:notification_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_notification(notification_id):
    """删除通知"""
    try:
        notification = Notification.query.get_or_404(notification_id)
        current_user_id = get_jwt_identity()
        
        # 检查通知状态，已发布的通知不能删除
        if notification.status == 'published':
            return jsonify({
                'success': False,
                'message': '已发布的通知不能删除'
            }), 400
        
        notification_title = notification.title
        
        db.session.delete(notification)
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='DELETE',
            table_name='notifications',
            record_id=notification_id,
            details=f'删除通知: {notification_title}'
        )
        
        return jsonify({
            'success': True,
            'message': '通知删除成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'删除通知失败: {str(e)}'
        }), 500

@notification_management_api.route('/api/admin/notifications/stats', methods=['GET'])
@jwt_required()
@admin_required
def get_notification_stats():
    """获取通知统计信息"""
    try:
        # 按状态统计
        unread_count = Notification.query.filter_by(status='unread').count()
        read_count = Notification.query.filter_by(status='read').count()
        deleted_count = Notification.query.filter_by(status='deleted').count()
        
        # 按类型统计
        system_count = Notification.query.filter_by(notification_type='system').count()
        intervention_count = Notification.query.filter_by(notification_type='intervention').count()
        vision_count = Notification.query.filter_by(notification_type='vision').count()
        share_count = Notification.query.filter_by(notification_type='share').count()
        
        # 今日新增
        from datetime import date
        today = date.today()
        today_count = Notification.query.filter(
            db.func.date(Notification.created_at) == today
        ).count()
        
        # 活跃通知（未删除）
        active_count = Notification.query.filter(
            Notification.status != 'deleted'
        ).count()
        
        return jsonify({
            'success': True,
            'data': {
                'unread': unread_count,
                'read': read_count,
                'deleted': deleted_count,
                'system': system_count,
                'intervention': intervention_count,
                'vision': vision_count,
                'share': share_count,
                'today': today_count,
                'active': active_count,
                'total': unread_count + read_count + deleted_count
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取统计信息失败: {str(e)}'
        }), 500

@notification_management_api.route('/api/admin/notifications/<int:notification_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_notification(notification_id):
    """获取单个通知详情"""
    try:
        notification = Notification.query.get_or_404(notification_id)
        
        return jsonify({
            'success': True,
            'data': notification.to_dict()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取通知失败: {str(e)}'
        }), 500
